import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  HttpStatus,
  HttpCode,
  BadRequestException,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { TodoService } from './todo.service';
import { UploadPicturesService } from '../common/upload/upload-pictures.service';
import { OssUtilService } from '../common/upload/oss-util.service';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';
import { CreateUploadPicturesDto } from './dto/create-upload-pictures.dto';
import { FinishTodoDto } from './dto/finish-todo.dto';
import { v4 as uuidv4 } from 'uuid';

@Controller('todo')
export class TodoController {
  constructor(
    private readonly todoService: TodoService,
    private readonly uploadPicturesService: UploadPicturesService,
    private readonly ossUtilService: OssUtilService,
  ) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  create(@Body() createTodoDto: CreateTodoDto) {
    return this.todoService.create(createTodoDto);
  }

  @Post('uploadimg')
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(@UploadedFile() file: any) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const fileName = file.originalname;
    const suffixName = fileName.substring(fileName.lastIndexOf('.'));
    const newFileName = uuidv4() + suffixName;

    try {
      const result = await this.ossUtilService.uploadFile(
        'hasmarket',
        'todo',
        newFileName,
        file.buffer,
      );

      return {
        success: true,
        data: {
          url: result.url,
          name: result.name,
          originalName: fileName,
          size: file.size,
          mimeType: file.mimetype,
        },
        message: '上传成功',
      };
    } catch (error) {
      console.error('OSS上传错误:', error);
      throw new BadRequestException(`上传失败: ${error.message}`);
    }
  }

  @Post('uploadreplyimg')
  @UseInterceptors(FileInterceptor('file'))
  async uploadReplyImage(@UploadedFile() file: any) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const fileName = file.originalname;
    const suffixName = fileName.substring(fileName.lastIndexOf('.'));
    const newFileName = uuidv4() + suffixName;

    try {
      const result = await this.ossUtilService.uploadFile(
        'hasmarket',
        'todoreply',
        newFileName,
        file.buffer,
      );

      return {
        success: true,
        data: {
          url: result.url,
          name: result.name,
          originalName: fileName,
          size: file.size,
          mimeType: file.mimetype,
        },
        message: '上传成功',
      };
    } catch (error) {
      console.error('OSS上传错误:', error);
      throw new BadRequestException(`上传失败: ${error.message}`);
    }
  }

  @Post('addtodoimageitem')
  async addTodoImageItem(@Body() uploadPicturesDto: CreateUploadPicturesDto) {
    try {
      const result = await this.uploadPicturesService.create(uploadPicturesDto);
      return {
        success: true,
        data: result,
        message: '添加图片记录成功',
      };
    } catch (error) {
      throw new BadRequestException('添加图片记录失败');
    }
  }

  @Post('deletetodoimg')
  async deleteTodoImage(@Body() data: { filename: string; serviceid: string }) {
    try {
      // 删除OSS文件（可选，根据需要开启）
      // await this.ossUtilService.deleteFile('hasmarket', 'todo', data.filename);
      
      // 删除数据库记录（软删除）
      await this.uploadPicturesService.softDeleteByServiceId(data.serviceid);

      return {
        success: true,
        message: '删除图片成功',
      };
    } catch (error) {
      throw new BadRequestException('删除图片失败');
    }
  }

  @Get('getminitodolist')
  getMiniTodoList(@Query() searchParams: any) {
    return this.todoService.getQuoteList(searchParams);
  }

  @Get('getminitododetail')
  getMiniTodoDetail(@Query('todoid') todoid: string) {
    return this.todoService.getTodoDetail(todoid);
  }

  @Get('getminitododetailwithreplies')
  getMiniTodoDetailWithReplies(@Query('todoid') todoid: string) {
    return this.todoService.getTodoDetailWithRepliesAndPictures(todoid);
  }

  @Post('addtodomanageitem')
  addTodoManageItem(@Body() todo: CreateTodoDto) {
    return this.todoService.create(todo);
  }

  @Post('updatetodomanageitem')
  updateTodoManageItem(@Body() todo: UpdateTodoDto) {
    if (!todo._Identify) {
      throw new BadRequestException('缺少_Identify字段');
    }
    return this.todoService.update(todo._Identify, todo);
  }

  @Get()
  findAll(@Query('page') page?: string, @Query('limit') limit?: string) {
    // 默认第1页，每页50条，确保参数是有效数字
    const pageNum = page ? Math.max(1, parseInt(page, 10) || 1) : 1;
    const pageSize = limit
      ? Math.max(1, Math.min(parseInt(limit, 10) || 50, 1000))
      : 50;
    return this.todoService.findAllPaginated(pageNum, pageSize);
  }

  @Get('search')
  search(
    @Query('q') q: string,
    @Query('keyword') keyword: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const searchTerm = q || keyword;
    if (!searchTerm) {
      throw new BadRequestException('搜索关键词不能为空');
    }
    const pageNum = page ? Math.max(1, parseInt(page, 10) || 1) : 1;
    const pageSize = limit
      ? Math.max(1, Math.min(parseInt(limit, 10) || 50, 1000))
      : 50;
    return this.todoService.searchByTitleOrContentPaginated(searchTerm, pageNum, pageSize);
  }



  @Get('status/:finished')
  findByStatus(
    @Param('finished') finished: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const isFinished = finished === 'true';
    const pageNum = page ? Math.max(1, parseInt(page, 10) || 1) : 1;
    const pageSize = limit
      ? Math.max(1, Math.min(parseInt(limit, 10) || 50, 1000))
      : 50;
    return this.todoService.findByStatusPaginated(isFinished, pageNum, pageSize);
  }



  @Get('type/:type')
  findByType(
    @Param('type') type: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const pageNum = page ? Math.max(1, parseInt(page, 10) || 1) : 1;
    const pageSize = limit
      ? Math.max(1, Math.min(parseInt(limit, 10) || 50, 1000))
      : 50;
    return this.todoService.findByTypePaginated(type, pageNum, pageSize);
  }

  @Get(':todoid')
  findOne(@Param('todoid') todoid: string) {
    return this.todoService.findByTodoid(todoid);
  }



  @Patch(':todoid/finish')
  markAsFinished(
    @Param('todoid') todoid: string,
    @Body() data: FinishTodoDto,
  ) {
    return this.todoService.markAsFinishedByTodoid(todoid, data.finished, data.finishtime);
  }

  @Patch(':todoid/postpone')
  markAsPostponed(@Param('todoid') todoid: string, @Body() data: { postponed?: boolean }) {
    return this.todoService.markAsPostponedByTodoid(todoid, data.postponed);
  }

  @Patch(':todoid/account-complete')
  markAsAccountCompleted(@Param('todoid') todoid: string) {
    return this.todoService.markAsAccountCompletedByTodoid(todoid);
  }

  @Delete(':todoid')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('todoid') todoid: string) {
    return this.todoService.deleteByTodoid(todoid);
  }

  @Post(':todoid/complete')
  markAsComplete(@Param('todoid') todoid: string) {
    return this.todoService.markAsCompleteByTodoid(todoid);
  }

  @Post(':todoid/extend')
  extendDeadline(@Param('todoid') todoid: string, @Body() data: { newDeadline: string }) {
    return this.todoService.extendDeadlineByTodoid(todoid, data.newDeadline);
  }

  @Get('completed/count')
  getCompletedCount() {
    return this.todoService.getCompletedCount();
  }

  // 解析和验证ID参数
  private parseId(id: string): number {
    const numId = parseInt(id, 10);
    if (isNaN(numId) || numId <= 0) {
      throw new BadRequestException(`Invalid ID: ${id}. ID must be a positive integer.`);
    }
    if (numId > Number.MAX_SAFE_INTEGER) {
      throw new BadRequestException(
        `Invalid ID: ${id}. ID must be less than ${Number.MAX_SAFE_INTEGER}.`,
      );
    }
    return numId;
  }
} 